package com.haoxuer.discover.common.freemarker;

import com.haoxuer.discover.common.utils.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.ext.beans.StringModel;
import freemarker.template.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class TextDirective implements TemplateDirectiveModel {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) {

        map = params;

        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        try {
            Map<String, TemplateModel> origMap = DirectiveUtils
                    .addParamsToVariable(env, paramWrap);
            handle(env);
            DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        }

    }
    public Object getObject(String name){
        TemplateModel model = (TemplateModel)map.get(name);
        if (model instanceof StringModel){
            StringModel temp= (StringModel) model;
           return temp.getWrappedObject();
        }
        if (model instanceof SimpleSequence){
            SimpleSequence temp= (SimpleSequence) model;
            try {
                return temp.toList();
            } catch (TemplateModelException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public abstract void handle(Environment env) throws IOException;

    private Map map;

    private Map getParams() {
        return map;
    }

    /**
     * 从标签里面获取一个int值
     *
     * @param name 参数
     * @return
     */
    public Integer getInt(String name) {
        Integer size = null;
        try {
            size = DirectiveUtils.getInt(name, map);

        } catch (Exception e) {

        }
        return size;
    }

    /**
     * 从标签里面获取一个int值
     *
     * @param name 参数
     * @param num  默认值
     * @return
     */
    public Integer getInt(String name, Integer num) {
        Integer size = null;
        try {
            size = DirectiveUtils.getInt(name, map);
            if (size == null) {
                size = num;
            }
        } catch (Exception e) {

        }
        return size;
    }

    public Long getLong(String name, Long num) {
        Long size = null;
        try {
            size = DirectiveUtils.getLong(name, map);
            if (size == null) {
                size = num;
            }
        } catch (Exception e) {

        }
        return size;
    }

    public String getString(String name, String defaul) {
        String result = null;
        try {
            result = DirectiveUtils.getString(name, map);
        } catch (Exception e) {

        }
        if (defaul == null) {
            defaul = "";
        }
        if (result == null) {
            result = defaul;
        }
        return result;
    }
}
